package com.briup.pts.service.impl;

import com.briup.pts.config.exception.ServiceException;
import com.briup.pts.config.response.ResultCode;
import com.briup.pts.domain.bean.Animal;
import com.briup.pts.domain.bean.Disease;
import com.briup.pts.domain.bean.DiseaseRecord;
import com.briup.pts.domain.vo.DiseaseRecordVO;
import com.briup.pts.mapper.AnimalMapper;
import com.briup.pts.mapper.DiseaseMapper;
import com.briup.pts.mapper.DiseaseRecordMapper;
import com.briup.pts.service.DiseaseRecordService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class DiseaseRecordImpl implements DiseaseRecordService {
    private final DiseaseRecordMapper diseaseRecordMapper;
    private final AnimalMapper animalMapper;
    private final DiseaseMapper diseaseMapper;


    @Override
    public List<Disease> queryAllDisease() {
        return diseaseRecordMapper.queryAllDisease();
    }

    @Override
    public PageInfo<DiseaseRecordVO> pageQuery(String drDId, String drStatus, Integer pageNum, Integer pageSize) {
        try (Page<DiseaseRecordVO> ignored = PageHelper.startPage(pageNum, pageSize)) {
            List<DiseaseRecordVO> records = diseaseRecordMapper.queryByConditional(drDId, drStatus);
            //转换并返回数据
            Page<DiseaseRecordVO> diseaserecordPage = (Page<DiseaseRecordVO>) records;
            return new PageInfo<>(diseaserecordPage);
        }
    }

    @Override
    public void batchDelete(List<Integer> drIds) {
        diseaseRecordMapper.batchDelete(drIds);
    }

    @Override
    public void saveOrUpdate(DiseaseRecord diseaseRecord) {
        //给某动物添加病症变化记录，必须保证该动物存在且处于养殖状态中
        String animalId = diseaseRecord.getDrAnimalId();
        Animal animal = animalMapper.queryByIdWithStatus(animalId, "养殖中");
        if (animal == null) {
            throw new ServiceException(ResultCode.ANIMAL_IS_NOT_EXISTS);
        }

        Disease disease = diseaseMapper.queryById(diseaseRecord.getDrDId());
        if (disease == null) {
            throw new ServiceException(ResultCode.DISEASE_IS_NOT_EXISTS);
        }

        //如果该动物处于养殖状态，那么继续添加或修改指标
        if (diseaseRecord.getDrId() != null) {
            //如果传输的信息id不为null，那么表示修改
            diseaseRecordMapper.updateDiseaseRecord(diseaseRecord);
        } else {
            //如果id为null，表示新增数据
            //确保同一个动物同一天只会记录一条数据
            DiseaseRecord diseaseRecord2 = diseaseRecordMapper.queryByAnimalIdWithTime(
                    animalId, diseaseRecord.getDrTime());

            if (diseaseRecord2 != null) {
                throw new ServiceException(ResultCode.DISEASE_RECORD_IS_EXISTS);
            }

            diseaseRecordMapper.addDiseaseRecord(diseaseRecord);
        }
        animal.setAHealthy("生病");
        animalMapper.updateAnimal(animal);
    }

}
